﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Syspetro.Core.Extensions
{
    public static class AssemblyHelper
    {
        public static List<Assembly> LoadFroms(string AssemblyMatch = null)
        {
            var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
            if (string.IsNullOrEmpty(AssemblyMatch))
            {
                //AssemblyMatch = Process.GetCurrentProcess().ProcessName;//不能兼容IIS
                var maindll = Directory.GetFiles(path, "*.exe");
                if(maindll?.Length > 0)
                {
                    //AssemblyMatch = maindll[0][0..^4];
                    AssemblyMatch = System.IO.Path.GetFileNameWithoutExtension(maindll[0]);
                }
            }
            if (!string.IsNullOrEmpty(AssemblyMatch))
            {
                var getFiles = Directory.GetFiles(path, "*.dll").Where(t => Match(t, AssemblyMatch));
                return getFiles.Select(Assembly.LoadFrom).ToList();
            }
            else
            {
                var getFiles = Directory.GetFiles(path, "*.dll");
                return getFiles.Select(Assembly.LoadFrom).ToList();
            }
        }
        /// <summary>
        /// 程序集是否匹配
        /// </summary>
        public static bool Match(string assemblyName, string AssemblyMatch)
        {
            assemblyName = Path.GetFileName(assemblyName);
            if (assemblyName.StartsWith($"{AppDomain.CurrentDomain.FriendlyName}.Views"))
                return false;
            if (assemblyName.StartsWith($"{AppDomain.CurrentDomain.FriendlyName}.PrecompiledViews"))
                return false;
            return Regex.IsMatch(assemblyName, AssemblyMatch, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        }
    }
}
